package main;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

// Nikolas Wolfe
// 2/20/09
// CIS 4930
// Candybox

// This implements a Candy

public class Candy
{
	private final int id;
	private boolean isNibbled;
	private static final AtomicInteger uniqueID = 
		new AtomicInteger(1);
	
	// thred-local variable which will be received by all 
	// threads executing upon a candy
	private ThreadLocal<Boolean> sampledByMe =
		new ThreadLocal<Boolean>() {
			public Boolean initialValue() {
				sampledByMe.set( Boolean.FALSE );
				return sampledByMe.get();
			}
	};
	
	// constructor
	public Candy()
	{
		// ensure a unique ID
		this.id = uniqueID.getAndIncrement();
		this.isNibbled = false;
	}
	
	public void nibble()
	{
		isNibbled = true;
		sampledByMe.set( Boolean.TRUE ); // this thread has now visited this candy
	}
	
	public boolean isNibbled()
	{
		return isNibbled;
	}
	
	public boolean isNibbledByCurrThread()
	{
		return sampledByMe.get(); // return value of thread-local variable
	}
	
	public String getStatus()
	{
		if( isNibbled ){ 
			return "nibbled"; 
		} else { return "unnibbled"; }
	}
	
	public int getId()
	{
		return id;
	}
	
	public String toString()
	{
		return "Candy #" + getId();
	}
}
